package org.space.galaxyCabinet.consumer;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.galaxy.common.mq.config.RabbitConfig;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.space.galaxyCabinet.domain.FreightChannel;
import org.space.galaxyCabinet.service.ChannelService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class DeviceConsumer {

    @Autowired
    private ChannelService channelService;

    @RabbitListener(queues = RabbitConfig.QUEUE_GOODS_OUT)
    public void receive(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        try {
            JSONObject jsonObject = JSON.parseObject(message);
            log.info("receive message: {}", message);
            FreightChannel freightChannel = new FreightChannel();
            freightChannel.setDeviceNo(jsonObject.getString("deviceNo"));
            String channelNo = jsonObject.getString("channelNo");
            freightChannel.setChannelNo(Long.parseLong(channelNo));
            Map<String, Object> data = new HashMap<>();
            data.put("orderNo", jsonObject.getString("orderNo"));
            freightChannel.setData(data);
            boolean orderFlag = channelService.out(freightChannel);
            if (orderFlag) {
                log.info("insert order success");
                channel.basicAck(deliveryTag, false);
            } else {
                log.error("处理订单消息失败, message: {}", message);
                try {
                    // 发生异常时拒绝消息，可以选择是否重新入队
                    channel.basicReject(deliveryTag, false);
                } catch (IOException ioException) {
                    log.error("拒绝消息失败", ioException);
                }
            }
        } catch (Exception e) {
            log.error("处理订单消息失败, message: {}", message, e);
            try {
                // 发生异常时拒绝消息，可以选择是否重新入队
                channel.basicReject(deliveryTag, false);
            } catch (IOException ioException) {
                log.error("拒绝消息失败", ioException);
            }
        }
    }
}
